﻿using System;
using System.Collections;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
using ConfigLibrary;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;
using AE.Net.Mail;

namespace MailClient.Queue
{
    /// <summary>
    /// sends outgoing emails asynchronously.  
    /// </summary>
    public sealed class outgoingrunner
    {

        /// <summary>
        /// Use to send email to a specific address.
        /// The default is set in the global Project settings
        /// </summary>
        private static readonly System.Lazy<outgoingrunner> lazy =
            new System.Lazy<outgoingrunner>(() => new outgoingrunner());

        public static outgoingrunner outgoing { get { return lazy.Value; } }
        private static ImapClient _client;
        private outgoingrunner()
        {

        }

        public void SetImapClient(ref ImapClient Client)
        {
            _client = Client;
        }

        static bool mailSent = false;
        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            String token = (string)e.UserState;

            if (e.Cancelled)
            {
                //Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                // Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
                // System.Windows.Forms.MessageBox.Show(e.Error.ToString());
            }
            else
            {
                //Console.WriteLine("Message sent.");
                //System.Windows.Forms.MessageBox.Show("email sent");
            }
            mailSent = true;
        }


        /// <summary>
        /// Call the function with the subject and message you want to send
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="msg"></param>
        public void sendmail(System.Net.Mail.MailMessage mail)
        {
            //MailAddress cc1 = new MailAddress(project_manager);
            // mail.CC.Add(cc1);

            MailAddress from = new MailAddress("rha@rhaaia.com", "RHA Email");
            mail.From = from;


            mail.BodyEncoding = System.Text.Encoding.UTF8;

            mail.SubjectEncoding = System.Text.Encoding.UTF8;
            _client.SendMail(mail);
            
        }
    }
}
